package cn.trigram.excel;

import cn.trigram.exception.GeneralException;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;

public class ExcelReader {

  /**
   * @param xmlCfgPath
   *     jxls-reader 的读取配置文件路径
   * @param dataXlsPath
   *     excel文件路径
   * @param beanMap
   *     数据读取后存储的Bean对象
   */
  public void read(final String xmlCfgPath, final String dataXlsPath,
      final Map<String, Object> beanMap) {

    ClassLoader ctLoader = Thread.currentThread().getContextClassLoader();
    try (
        InputStream xmlCfgStream = new BufferedInputStream(
            ctLoader.getResourceAsStream(xmlCfgPath));
        InputStream dataXlsStream = new BufferedInputStream(
            ctLoader.getResourceAsStream(dataXlsPath));
    ) {
      XLSReader mainReader = ReaderBuilder.buildFromXML(xmlCfgStream);
      XLSReadStatus readStatus = mainReader.read(dataXlsStream, beanMap);
      if (!readStatus.isStatusOK()) {
        List<XLSReadMessage> readMessages = readStatus.getReadMessages();
        String failMsg = readMessages.stream()
            .map(xrm -> xrm.getMessage() + "【" + xrm.getException().getLocalizedMessage() + "】")
            .collect(
                Collectors.joining(System.lineSeparator()));
        throw new GeneralException(failMsg);
      }
    } catch (Exception e) {
      throw new GeneralException(String.format("使用JXLS2读取Excel文件%s失败", dataXlsPath), e);
    }
  }

}
